package top.heue.test.http

import com.hjq.http.config.IRequestApi
import com.hjq.http.request.HttpRequest
import com.orhanobut.hawk.Hawk


object HttpCacheManager {
    private val hcc = Hawk.getSelect("http_cache_content")
    private val hct = Hawk.getSelect("http_cache_time")

    /**
     * 生成缓存的 key
     */
    fun generateCacheKey(httpRequest: HttpRequest<*>): String {
        val requestApi: IRequestApi = httpRequest.requestApi
        return """
            UserId
            ${requestApi.api}
            ${Hawk.serialize(requestApi)}
            """.trimIndent()
    }

    /**
     * 读取缓存
     */
    fun readHttpCache(cacheKey: String?): String? {
        val cacheValue: String = hcc.get(cacheKey, "")
        return if ("" == cacheValue || "{}" == cacheValue) {
            null
        } else cacheValue
    }

    /**
     * 写入缓存
     */
    fun writeHttpCache(cacheKey: String?, cacheValue: String?): Boolean {
        return hcc.put(cacheKey, cacheValue)
    }

    /**
     * 清理缓存
     */
    fun clearCache() {
        hcc.deleteAll()
        hct.deleteAll()
    }

    /**
     * 获取 Http 写入缓存的时间
     */
    fun getHttpCacheTime(cacheKey: String?): Long {
        return hct.get(cacheKey, 0)
    }

    /**
     * 设置 Http 写入缓存的时间
     */
    fun setHttpCacheTime(cacheKey: String?, cacheTime: Long): Boolean {
        return hct.put(cacheKey, cacheTime)
    }

    /**
     * 判断缓存是否过期
     */
    fun isCacheInvalidate(cacheKey: String?, maxCacheTime: Long): Boolean {
        if (maxCacheTime == Long.MAX_VALUE) {
            // 表示缓存长期有效，永远不会过期
            return false
        }
        val httpCacheTime = getHttpCacheTime(cacheKey)
        return if (httpCacheTime == 0L) {
            // 表示不知道缓存的时间，这里默认当做已经过期了
            true
        } else httpCacheTime + maxCacheTime < System.currentTimeMillis()
    }
}